import { createRouter, createWebHistory } from 'vue-router'
import auth from '@/utils/auth'
// import Vue from 'vue'
const routes = [
  {
    path: '/',
    component: () => import('../layouts/MainLayout.vue'),
    children: [
      { path: '', redirect: '/dashboard' },
      { path: 'dashboard', component: () => import('../views/dashboard/Index.vue') },
      { path: 'users', component: () => import('../views/users/Index.vue') },
      { path: 'permission', component: () => import('../views/permission/Index.vue') },
      { path: 'system', component: () => import('../views/system/Index.vue') },
      { path: 'logs', component: () => import('../views/logs/Index.vue') },
      { path: 'help', component: () => import('../views/help/Index.vue') },
      { path: 'role', component: () => import('../views/role/Index.vue') },
      { path: 'profile', component: () => import('../views/users/Profile.vue') },
    ]
  },
  { path: '/login', component: () => import('../views/auth/Login.vue') },
  { path: '/register', component: () => import('../views/auth/Register.vue') },
  { path: '/forgot', component: () => import('../views/auth/Forgot.vue') },
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})


// 路由守卫：判断是否登录
router.beforeEach(async (to, from, next) => {
  const publicPages = ['/login', '/register', '/forgot']
  const isPublic = publicPages.includes(to.path)

  // 公开页面直接放行
  if (isPublic) {
    next()
    return
  }

  // 非公开页面检查登录状态和token是否过期
  if (auth.checkLoginStatus()) {
    next()
  } else {
    // 已在checkLoginStatus中处理跳转
    // 如果token过期，auth.logout()会自动跳转到登录页
    next(false) // 阻止路由跳转
  }
})
// 路由后置守卫：路由切换后隐藏进度条
// router.afterEach(() => {
//   // 在路由切换后隐藏进度条
//   Vue.$Progress.finish();
// });


export default router

